package testnode;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.UUID;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;

import rmi.*;

/**
 * Verwaltet das TestNode Objekt und bindet es an die RMI Registry.
 * 
 */
public class Test extends RmiStarter {
	
	private static Test instance = null;
	private String uniqueId;
	private final TestNode node;
	
	Logger logger = Logger.getLogger(this.getClass());
	
	private Test() throws ConfigurationException
	{
		super();
		TestNode newNode;
		try
		{
			newNode = new TestNode();
		}
		catch(Exception e)
		{
			newNode = null;
			logger.error("Fehler beim Starten des TestNodes", e);
		}
		this.node = newNode;
	}

	public static Test getInstance() throws ConfigurationException {
		if (instance == null) 
			instance = new Test();
		
		return instance;
	}
	
	/**
	 * Bindet den TestNode an die RMI Registry.
	 * @param registryHost die Adresse des Nameservice 
	 * @param port der Port
	 */
	public void bindToRegistry(String registryHost, int port)
	{ 
        try {
            logger.debug("Bind TestNode with uniqueId: " + getUniqueId());
            Registry registry;
            if(port >= 0)
            	registry = LocateRegistry.getRegistry(registryHost, port);
            else
            	registry = LocateRegistry.getRegistry(registryHost);
            registry.rebind(uniqueId, node);
        }
        catch(Exception e) {
        	logger.error("TestNode konnte nicht an Registry gebunden werden!", e);
        }
	}

	/**
	 * Bindet den TestNode an die RMI Registry. Als Port wird der Standardport verwendet (normalerweise 1099).
	 * @param registryHost die Adresse des Nameservice
	 */
	public void bindToRegistry(String registryHost)
	{
		bindToRegistry(registryHost, -1);
	}
	
	public String getUniqueId() {
		synchronized(this) {
			if(uniqueId == null)
				this.uniqueId = UUID.randomUUID().toString();
		}
		return this.uniqueId;
	}

	@Override
	public void doCustomRmiHandling() {
		
	}
}
